<template>
  <div class="unarranged-container">
    <div class="filter-section">
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form ">
        <el-form-item label="授权名称" class="el-form-item">
            <el-input v-model="searchForm.username" placeholder="请输入授权名称" clearable />
          </el-form-item>
        <el-form-item label="考生姓名" class="el-form-item">
            <el-input v-model="searchForm.candidateName" placeholder="请输入考生姓名" clearable />
          </el-form-item>
          <el-form-item label="证件号码" class="el-form-item">
            <el-input v-model="searchForm.idNumber" placeholder="请输入证件号码" clearable />
          </el-form-item>
        
          <el-form-item label="报考专业" class="el-form-item">
              <el-select v-model="searchForm.major" placeholder="请选择报考专业" clearable>
                <el-option v-for="item in majorData" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="报考等级" class="el-form-item">
              <el-select v-model="searchForm.level" placeholder="请选择报考等级" clearable>
                <el-option v-for="item in levelData" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="报考日期" class="el-form-item">
              <el-date-picker
                v-model="searchForm.applicationDate"
                type="date"
                placeholder="请选择报考日期"
                value-format="YYYY-MM-DD"
                />
          </el-form-item>
            <el-form-item label="准考证号" class="el-form-item">
            <el-input v-model="searchForm.admissionTicketNumber" placeholder="请输入准考证号" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" class="Button">查询</el-button>
            <el-button @click="resetForm" class="Button">重置</el-button>
       
          </el-form-item>
          <el-form-item class="DowloadBox">
            <el-button type="primary" class="Button" @click="exportExamReport" :loading="exportLoading" :disabled="!tableData.length"> 导出已排考报表 </el-button>
          </el-form-item>
          <el-form-item class="DowloadBox">
            <el-button type="primary" class="Button" @click="batchDownloadAdmissionTickets" :loading="downloadTicketsLoading" :disabled="!tableData.length"> 批量下载准考证 </el-button>
          </el-form-item>
            <el-form-item class="DowloadBox">
            <el-button type="primary" class="Button" @click="batchDownloadScoreSheets" :loading="downloadSheetsLoading" :disabled="!tableData.length"> 批量下载评分表 </el-button>
          </el-form-item>
      
      </el-form>
     
    </div>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="tableData" border class="el-table">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="candidateName" label="考生姓名" width="100" />
      <el-table-column prop="candidateNamePinyin" label="姓名拼音" width="160" />
      <el-table-column prop="gender" label="性别" width="60" />
      <el-table-column prop="major" label="报考专业" width="100" />
      <el-table-column prop="level" label="报考等级" width="100" />
      <el-table-column prop="admissionTicketNumber" label="准考证号" width="220" />
      <el-table-column prop="idType" label="证件类型" width="100" />
      <el-table-column prop="idNumber" label="证件号码" width="220" />
      <el-table-column prop="applicationDate" label="报考日期" width="180" />
      <el-table-column prop="campus" label="所在校区" width="180" />
      <el-table-column prop="currentAddress" label="现居地址" width="180" />

      <!-- 操作列 -->
      <el-table-column label="操作" width="400" fixed="right">
        <template #default="{ row }">
          <div class="button-group">
            <el-button type="primary" size="small" class="mini-btn" @click="handleView(row)">查看</el-button>
          
            <el-button type="primary" size="small" class="mini-btn" @click="downloadAdmissionTicket(row)" :disabled="!row.admissionTicket">准考证</el-button>
            <el-button type="primary" size="small" class="mini-btn" @click="downloadScoreSheet(row)" :disabled="!row.scoreSheet">评分表</el-button>
            <template v-if="row.scoreStatus">
              <el-button type="info" size="small" class="mini-btn" @click="handleViewScore(row)">查看成绩</el-button>
            </template>
            <template v-else>
              <el-button type="success" size="small" class="mini-btn" @click="handleScore(row)">成绩录入</el-button>

              <!-- <el-tooltip :content="row.examApplication.status_id !== 4 ? '当前考试未结束，暂不能录入成绩' : ''" placement="top" effect="light" :disabled="row.examApplication.status_id === 4">
                  <el-button type="success" size="small" class="mini-btn" @click="handleScore(row)" :disabled="row.examApplication.status_id !== 4">成绩录入</el-button>
                </el-tooltip> -->
            </template>
            <el-button v-if="row.examApplication.status_id !== 4" type="danger" size="small" class="mini-btn" @click="handleCancelArrange(row)">取消排考</el-button>
          </div>
        </template>
      </el-table-column>
          <template #empty>
             <el-empty description="暂无数据" />
           </template>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[13, 24, 50, 100,200]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="dialogVisible" title="考生详情" width="800px">
      <div class="detail-content">
        <el-descriptions :column="2" border :label-width="120">
          <el-descriptions-item label="考生姓名">{{ currentRow.candidateName }}</el-descriptions-item>
          <el-descriptions-item label="姓名拼音">{{ currentRow.candidateNamePinyin }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ currentRow.gender }}</el-descriptions-item>
          <el-descriptions-item label="民族">{{ currentRow.ethnicity }}</el-descriptions-item>
          <el-descriptions-item label="准考证号">{{ currentRow.admissionTicketNumber }}</el-descriptions-item>
          <el-descriptions-item label="证件号码">{{ currentRow.idNumber }}</el-descriptions-item>
          <el-descriptions-item label="报考专业">{{ currentRow.major }}</el-descriptions-item>
          <el-descriptions-item label="报考等级">{{ currentRow.level }}</el-descriptions-item>
          <el-descriptions-item label="所在校区">{{ currentRow.campus }}</el-descriptions-item>
          <el-descriptions-item label="报考日期">{{ currentRow.applicationDate }}</el-descriptions-item>
          <el-descriptions-item label="当前地址" :span="2">{{ currentRow.currentAddress }}</el-descriptions-item>
          <el-descriptions-item label="家长电话">{{ currentRow.parentPhone }}</el-descriptions-item>
          <el-descriptions-item label="指导老师">{{ currentRow.instructor }}</el-descriptions-item>
          <el-descriptions-item label="指导老师电话" :span="2">{{ currentRow.instructorPhone }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加成绩录入对话框 -->
    <el-dialog v-model="scoreDialogVisible" title="成绩录入" width="500px">
          <el-form-item label="考生姓名" label-width="100px">
            <span>{{ currentItem.candidateName }}</span>
          </el-form-item>
          <el-form-item label="姓名拼音" label-width="100px">
            <span>{{ currentItem.candidateNamePinyin }}</span>
          </el-form-item>
          <el-form-item label="考生性别" label-width="100px">
            <span>{{ currentItem.gender }}</span>
          </el-form-item>
          <el-form-item label="准考证号" label-width="100px">
            <span>{{ currentItem.admissionTicketNumber }}</span>
          </el-form-item>
          <el-form-item label="证件号码" label-width="100px">
            <span>{{ currentItem.idNumber }}</span>
          </el-form-item>
          <el-form-item label="报考专业" label-width="100px">
            <span>{{ currentItem.major }}</span>
          </el-form-item>
          <el-form-item label="报考等级" label-width="100px">
            <span>{{ currentItem.level }}</span>
          </el-form-item>
  
      
      <el-form :model="scoreForm" label-width="100px">
        <el-form-item label="成绩状态">
          <el-select v-model="scoreForm.scoreStatus" placeholder="请选择成绩状态" style="width: 80%">
            <el-option label="通过" value="通过" />
            <el-option label="未通过" value="未通过" />
            <el-option label="缺考" value="缺考" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="分数" v-if="scoreForm.scoreStatus !== '缺考'">
          <el-input v-model="scoreForm.score" type="number" placeholder="请输入分数" style="width: 80%" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="scoreDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitScore">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 在其他对话框后面添加查看成绩对话框 -->
    <el-dialog v-model="scoreViewDialogVisible" title="考试成绩" width="400px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="考生姓名">{{ currentRow.candidateName }}</el-descriptions-item>
        <el-descriptions-item label="考试等级">{{ currentRow.level }}</el-descriptions-item>
        <el-descriptions-item label="考试专业">{{ currentRow.major }}</el-descriptions-item>
        <el-descriptions-item label="成绩状态">{{ currentRow.scoreStatus }}</el-descriptions-item>
        <!-- <el-descriptions-item label="考试分数" v-if="currentRow.scoreStatus !== '缺考'">
          {{ currentRow.score }}
        </el-descriptions-item> -->
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="scoreViewDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted,watch, computed } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Plus, Document, Delete } from '@element-plus/icons-vue';
  import Http from '@/utils/http';
  import { areaOptions } from '@/utils/area-data';
  import OSS from 'ali-oss';
  import { imgUrls } from '@/utils/utils';
  import { exportRegistrationForm } from '@/utils/Api';
  import { getSubuser, getExamApplications } from '@/api/api';
  import { useMainStore } from '@/stores/useMain';

  // 2. 在任何其他代码之前定义 loading
  const loading = ref(false);
  const mainStore = useMainStore();

  // 3. 其他状态变量
  const dialogVisible = ref(false);
  const scoreDialogVisible = ref(false);
  const scoreViewDialogVisible = ref(false);
  const currentRow = ref({});
  const tableData = ref([]);
  const currentPage = ref(1);
  const pageSize = ref(13);
  const total = ref(100);
  const user_id = ref('');
  const institutionOptions = ref([]);
  const declarationOptions = ref([]);
  const exportLoading = ref(false);
  const downloadTicketsLoading = ref(false);
  const downloadSheetsLoading = ref(false);


  const majorData = ref(['主持']);
  const levelData = ref(['1级','2级','3级','4级','5级','6级','7级','8级','9级','10级']);

  // 4. 响应式对象
  const searchForm = reactive({
    username: '',  // 授权名称
    candidateName: '',  // 考生姓名
    idNumber:'', // 证件号码
    major:'',// 报考专业
    level: '',  // 报考等级
    applicationDate:'', // 报考日期
    admissionTicketNumber:'',// 准考证号
  });

  const scoreForm = reactive({
    examRegistrationId: '',
    scoreStatus: '',
    score: '',
  });


  const currentItem = ref(''); // 当前选择学生信息

  // 5. 生命周期钩子
  onMounted(() => {
    getInstitutions();
  });

  // 获取机构列表
  const getInstitutions = async () => {
    try {
      const data = await getSubuser();
      institutionOptions.value = data;

    
      getExamList();
    } catch (error) {
      console.error('获取机构列表失败：', error);
    }
  };

  // 获取考级申报列表
  const getDeclarationList = async () => {
    try {
      // 当 user_id 为空时，获取所有考级申报
      const data = await getExamApplications(user_id.value || undefined);
      declarationOptions.value = data.items || [];
    } catch (error) {
      ElMessage.error('获取考级申报列表失败');
      console.error('获取考级申报列表失败：', error);
    }
  };

  // 获取未安排考场的考生列表数据
  const getExamList = async () => {
    loading.value = true;
    try {
      const params = {
        page: currentPage.value,
        pageSize: pageSize.value,
        hasAdmissionTicket: true,
        ...searchForm,
      };

      const res = await Http.post({
        url: '/yp_admin/applyList',
        data: params,
      });
      tableData.value = res.data.list;
      total.value = res.data.pagination.total;
    } catch (error) {
      console.error('获取考生列表失败：', error);
      ElMessage.error('获取考生列表失败');
    } finally {
      loading.value = false;
    }
  };

  // 重置表单
  const resetForm = () => {
    searchForm.candidateName = '';
    searchForm.level = '';
    searchForm.username = '';
    searchForm.idNumber = '';
    searchForm.major = '';
    searchForm.admissionTicketNumber = '';
    searchForm.applicationDate = '';
    // 只在有多个机构选项时才重置 user_id
    if (institutionOptions.value.length > 1) {
      user_id.value = '';
    }
    handleSearch();
  };

  // 搜索方法
  const handleSearch = () => {
    currentPage.value = 1;
    getExamList();
  };

  const handleSizeChange = (val) => {
    pageSize.value = val;
    getExamList();
  };

  const handleCurrentChange = (val) => {
    currentPage.value = val;
    getExamList();
  };

  // 监听机构选择变化
  watch(user_id, (newVal) => {
    if (newVal) {
      // 只在 user_id 有值时才获取数据
      getDeclarationList();
      handleSearch();
    }
  });



  // 在 script setup 部分添加以下方法
  const handleCancel = (row) => {
    ElMessageBox.confirm('确定要取消该考生的考场安排吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      try {
        await Http.post({
          url: '/yp_admin/deleteApply',
          data: { id: row.id },
        });
        ElMessage.success('取消成功');
        getExamList();
      } catch (error) {
        ElMessage.error('取消失败');
      }
    });
  };

  const downloadAdmissionTicket = (row) => {
    if (row.admissionTicket) {
      const downloadUrl = imgUrls(row.admissionTicket);
      // 在新标签页打开文件
      window.open(downloadUrl, '_blank');

      ElMessage.success('下载成功');
    } else {
      ElMessage.warning('准考证文件不存在');
    }
  };

  const downloadScoreSheet = (row) => {
    if (row.scoreSheet) {
      const downloadUrl = imgUrls(row.scoreSheet);
      window.open(downloadUrl, '_blank');

      ElMessage.success('下载成功');
    } else {
      ElMessage.warning('评分表文件不存在');
    }
  };

  // 成绩录入
  const handleScore = (row) => {
    currentItem.value = row;
    scoreDialogVisible.value = true;
    scoreForm.examRegistrationId = row.id;
    scoreForm.scoreStatus = '';
    scoreForm.score = '';
    console.log(currentItem.value,'currentItem.value');
    
  };

  const handleView = (row) => {
    currentRow.value = { ...row };
    dialogVisible.value = true;
  };

  const handleViewScore = (row) => {
    currentRow.value = { ...row };
    scoreViewDialogVisible.value = true;
  };

  const submitScore = async () => {
    try {
      if (!scoreForm.scoreStatus) {
        return ElMessage.warning('请选择成绩状态');
      }

      // if (scoreForm.scoreStatus !== '缺考' && !scoreForm.score) {
      //   return ElMessage.warning('请输入分数');
      // }

      const res = await Http.post({
        url: '/yp_admin/markScore',
        data: {
          examRegistrationId: scoreForm.examRegistrationId,
          scoreStatus: scoreForm.scoreStatus,
          score: 0,
        },
      });
      if (res.code === 200) {
        ElMessage.success('成绩录入成功');
        scoreDialogVisible.value = false;
        getExamList(); // 刷新列表
      } else {
        ElMessage.error(res.msg);
      }

      getExamList(); // 刷新列表
    } catch (error) {
      ElMessage.error('成绩录入失败');
    }
  };

  // 计算属性：判断是否可以批量录入成绩
  const canBatchInputScores = computed(() => {
    return tableData.value.some((row) => row.examApplication.status_id === 4 && !row.scoreStatus);
  });

  // 导出已排考报表
  const exportExamReport = async () => {
    exportLoading.value = true;
    try {
      const params = {
       
        hasAdmissionTicket: true,
        ...searchForm,
      };
      exportRegistrationForm(params);
    } catch (error) {
      ElMessage.error('导出失败');
    } finally {
      exportLoading.value = false;
    }
  };

  // 批量下载准考证
  const batchDownloadAdmissionTickets = async () => {
    downloadTicketsLoading.value = true;
    try {
      const validRows = tableData.value.filter((row) => row.admissionTicket);
      if (validRows.length === 0) {
        return ElMessage.warning('没有可下载的准考证');
      }

      const res = await Http.post({
        url: '/yp_admin/batchDownloadAdmissionTicket',
        data: {
         
          hasAdmissionTicket: true,
          ...searchForm,
        },
      });

      // 创建下载链接
      const downloadUrl = imgUrls(res.data.url);
      const link = document.createElement('a');
      link.href = downloadUrl;
      link.download = res.data.fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      ElMessage.success('准考证下载成功');
    } catch (error) {
      ElMessage.error('下载准考证失败');
    } finally {
      downloadTicketsLoading.value = false;
    }
  };

  // 批量下载评分表
  const batchDownloadScoreSheets = async () => {
    downloadTicketsLoading.value = true;
    try {
      const validRows = tableData.value.filter((row) => row.admissionTicket);
      if (validRows.length === 0) {
        return ElMessage.warning('没有可下载的评分表');
      }

      const res = await Http.post({
        url: '/yp_admin/batchDownloadScoreSheet',
        data: {
         
          hasAdmissionTicket: true,
          ...searchForm,
        },
      });

      const downloadUrl = imgUrls(res.data.url);
      const link = document.createElement('a');
      link.href = downloadUrl;
      link.download = res.data.fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      ElMessage.success('下载成功');
    } catch (error) {
      ElMessage.error('下载失败');
    } finally {
      downloadTicketsLoading.value = false;
    }
  };

  // 批量录入成绩
  const batchInputScores = () => {
    ElMessageBox.confirm('确定要进入批量录入成绩模式吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info',
    }).then(() => {
      // 这里可以跳转到批量录入页面或打开批量录入对话框
      ElMessage.info('功能开发中');
    });
  };

  // 在 script setup 部分添加取消排考方法
  const handleCancelArrange = (row) => {
    ElMessageBox.confirm('确定要取消该考生的排考吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      try {
        const res = await Http.post({
          url: '/yp_admin/cancelArranging',
          data: { id: row.id },
        });

        if (res.code === 200) {
          ElMessage.success('取消排考成功');
          getExamList(); // 刷新列表
        } else {
          ElMessage.error(res.msg || '取消排考失败');
        }
      } catch (error) {
        ElMessage.error('取消排考失败');
      }
    });
  };
</script>

<style scoped lang="scss">

  .unarranged-container {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    padding: 20px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }

  .filter-section {
    width: 100%;
    display: flex;
    flex-direction: column;
    .search-form {
      width: 100%;
      display: flex;
      flex-wrap: wrap;

    
    }
  }

  .el-form--inline .el-form-item {
    margin-right: 10px !important;
    :deep(.el-form-item__content){
      width: 180px !important;
      .el-input{
        height:100%;
      }
    }
  }
  .el-select,.el-input{
    width:180px;
  }


  :deep(.el-input__wrapper) {
    height: 40px;
    line-height: 40px;
  }
 
  :deep(.el-form-item__label) {
    height: 40px;
    line-height: 40px;
    padding-right: 12px;
    white-space: nowrap;
  }

  .DowloadBox{
    width:140px;
    
  }

 
  .el-table {
    width: 100%;
    flex: 1;
  }

  .button-group {
      display: flex;
     justify-content: center;

     .mini-btn{
      width: 70px;
      height: 30px;
      padding: 3px 6px;
      font-size: 12px;
      margin: 0 10px;
     }
  
  }

  

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  
  .detail-content {
    padding: 20px;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
  .curentData{
    width:100%;
    display: flex;
    align-content: center;
    margin-bottom: 12px;

    .name{
      color:#606266;
      font-size: 14px;
      padding-left:29px;
    }
    .content{
      margin-left:20px;
      font-size: 14px;
      color:#303133;
    }
  }
</style>
